import React, { useEffect, useState, useRef } from 'react';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Tooltip, message } from 'antd';
import Highlighter from 'react-highlight-words';
import axios from '@/components/service/request';
import EditModal from '@/components/EditModal/index';
import DeleteButton from '@/components/DeleteButton/index';
import ParseFileText from '@/components/AnalyzeFileText/index'; // 引入解析文件的组件
import FetchImagesText from '@/components/FetchImagesText/index'; // 引入解析文件的组件

const History = () => {
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [data, setData] = useState([]);
    const [editingRecord, setEditingRecord] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);
    // 定义文件路径和弹窗可见状态
    const [selectedFilePath, setSelectedFilePath] = useState(null); 
    const [isViewModalVisible, setViewModalVisible] = useState(false); 


    const parsedUserData = JSON.parse(localStorage.getItem('user'));
    const currentUser = parsedUserData?.data?.userName;

    useEffect(() => {
        const fetchData = () => {
            axios.get('/filedata/get')
                .then(response => {
                    const updatedData = response.data.map(item => ({
                        ...item,
                        user_name: currentUser,
                    }));
                    setData(updatedData);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                });
        };

        fetchData();
        const intervalId = setInterval(fetchData, 60000);
        return () => clearInterval(intervalId);
    }, [currentUser]);

    const handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

        // 解析成功后更新指定记录的状态
        const updateRecordState = (filePath) => {
            setData(prevData =>
                prevData.map(item =>
                    item.filePath === filePath ? { ...item, state: 1 } : item
                )
            );
        };

    const handleView = (filePath) => {
        setSelectedFilePath(filePath);
        setViewModalVisible(true);
    };
    const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
    };

    const getColumnSearchProps = (dataIndex) => ({
        filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
            <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{ marginBottom: 8, display: 'block' }}
                />
                <Space>
                    <Button type="primary" onClick={() => handleSearch(selectedKeys, confirm, dataIndex)} icon={<SearchOutlined />} size="small" style={{ width: 90 }}>
                        搜索
                    </Button>
                    <Button onClick={() => clearFilters && handleReset(clearFilters)} size="small" style={{ width: 90 }}>
                        重置
                    </Button>
                    <Button type="link" size="small" onClick={() => {
                        confirm({ closeDropdown: false });
                        setSearchText(selectedKeys[0]);
                        setSearchedColumn(dataIndex);
                    }}>
                        筛选
                    </Button>
                    <Button type="link" size="small" onClick={() => close()}>
                        关闭
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered) => (
            <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
        ),
        onFilter: (value, record) => record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }} searchWords={[searchText]} autoEscape textToHighlight={text ? text.toString() : ''} />
            ) : (
                text
            ),
    });

    const handleEdit = (record) => {
        setEditingRecord(record);
        setIsModalVisible(true);
    };

    const handleUpdate = (updatedRecord) => {
        setData(prevData => prevData.map(item => item.id === updatedRecord.id ? updatedRecord : item));
    };

    const handleDelete = (filePath) => {
        setData(prevData => prevData.filter(item => item.filePath !== filePath));
    };

    const handleDownload = async (filePath, fileName) => {
        try {
            const response = await axios.post('/filedata/download', null, { 
                params: { fileUrl: filePath }, 
                responseType: 'blob' 
            });

            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            message.success('文件下载成功');
        } catch (error) {
            console.error('Error downloading file:', error);
            message.error('文件下载失败');
        }
    };

    const columns = [
        {
            title: '用户名',
            dataIndex: 'user_name',
            key: 'user_name',
            width: '10%',
            ...getColumnSearchProps('user_name'),
        },
        {
            title: '时间',
            dataIndex: 'data',
            key: 'data',
            width: '18%',
            ...getColumnSearchProps('data'),
            sorter: (a, b) => a.data.length - b.data.length,
            sortDirections: ['descend', 'ascend'],
        },
        {
            title: '文件名',
            dataIndex: 'fileName',
            key: 'fileName',
            width: '18%',
            ...getColumnSearchProps('fileName'),
            render: (text, record) => (
                <Tooltip title={`点击下载 ${record.fileName}`}>
                    <Button type="link" onClick={() => handleDownload(record.filePath, record.fileName)}>
                        {record.fileName}
                        <DownloadOutlined />
                    </Button>
                </Tooltip>
            ),
        },
        {
            title: '是否解析',
            dataIndex: 'state',
            key: 'state',
            width: '16%',
            render: (text, record) => (
                text === 1 ? (
                    '已解析'
                ) : (
                    <ParseFileText 
                        filePath={record.filePath} 
                        onParseSuccess={() => updateRecordState(record.filePath)} // 传递回调
                    />
                )
            ),
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: '22%',
            ...getColumnSearchProps('remark'),
            render: (text) => <div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{text}</div>,
        },
        {
            title: '操作',
            key: 'action',
            width: '16%',
            render: (text, record) => (
                <Space size="middle">
                    <Button style={{color:"blue",borderColor: "blue",}}onClick={() => handleView(record.filePath)}>查看</Button>
                    <Button onClick={() => handleEdit(record)}>编辑</Button>
                    <DeleteButton record={record} onDelete={handleDelete} />
                    
                </Space>
            ),
        },
    ];

    return (
        <>
            <Table 
                columns={columns} 
                dataSource={data} 
                rowKey="id" 
                rowClassName={() => "editable-row"} 
                style={{ tableLayout: 'fixed' }}
            />
            {editingRecord && (
                <EditModal
                    record={editingRecord}
                    visible={isModalVisible}
                    onUpdate={handleUpdate}
                    onClose={() => setIsModalVisible(false)}
                />
            )}
            {/* 图片查看弹窗 */}
            <FetchImagesText
                filePath={selectedFilePath}
                visible={isViewModalVisible}
                onClose={() => setViewModalVisible(false)}
            />
        </>
    );
};

export default History;
